package com.thomas.jaspersoft.studio.example.controller;

import java.io.IOException;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.thomas.jaspersoft.studio.example.request.ReportRequest;
import com.thomas.jaspersoft.studio.example.service.JasperExampleService;
import net.sf.jasperreports.engine.JRException;

@Controller
public class JasperController { 
	
	private static final Log LOG = LogFactory.getLog(JasperController.class);
	private final JasperExampleService jasperExampleService;
		
	public JasperController(final JasperExampleService jasperExampleService){
		this.jasperExampleService = jasperExampleService;
	}
	
	@GetMapping("/report/{reportName}")
	public String generateReport(@PathVariable(value="reportName") String reportName,
								 @RequestParam(value="reportType", defaultValue="pdf", required=false) String reportType,
								 @RequestParam(value="resourceType", defaultValue="json", required=false) String resourceType,
								 Model model) throws JRException, SQLException, IOException{		
		ReportRequest reportRequest = new ReportRequest();
		reportRequest.setReportType(reportType);
		reportRequest.setReportName(reportName);
		reportRequest.setResourceType(resourceType);
		String generatedReportName = this.jasperExampleService.generateReport(reportRequest);
		model.addAttribute("reportName", generatedReportName);
		return "result";
	}
	

	
	@RequestMapping({"", "/", "/home"})
	public String home(){
		return "home";
	}
	
	
}
